package com.edais.service.imp;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.ShopBuyDao;
import com.edais.domain.WeixinMediaBinding;
import com.edais.mina.TcpMinaClient;
import com.edais.service.CaptchaService;
import com.edais.service.SMSService;
import com.edais.service.ShopBuyService;
import com.edais.service.WeixinBindingService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.JsonUtil;
import com.edais.util.weixinAbout.SendWeiXinUtil;

@Service

public class ShopBuyServiceImpl implements ShopBuyService {
	
	private static final Log logger = LogFactory.getLog(ShopBuyServiceImpl.class);

	@Autowired
	private ShopBuyDao shopBuyDao;
	
	@Autowired
	private SMSService sMSService;

	@Autowired
	private WeixinBindingService weixinBindingService;
	
	@Autowired
	private CaptchaService captchaService;
	/**
	 * 生成商城理财信息
	 */
	@Override
	@Transactional
	public Map<String, Object> createOrderFinance(Map<String, String> map)
			throws Exception {
		Map<String, Object> retMap = new HashMap<String,Object>();
		if (map==null) {
			retMap.put("rescode", Consts.CHECK_CODE);
			retMap.put("resmsg", "");
			retMap.put("resmsg_cn", "参数错误!");
			return retMap;
		}
		
		String buyOrderId = "";
		
		// E400001
		Map<String,Object> resMap = buyLoan(map);
		
		if (resMap == null || !"00000".equals(resMap.get("rescode"))) {
			logger.error("余额购买散标异常" + resMap.get("resmsg"));
			retMap.put("rescode", Consts.CHECK_CODE);
			retMap.put("resmsg", "");
			retMap.put("resmsg_cn", "商城购买散标失败！");
			return retMap;
		} else {
			// 获取订单号
			buyOrderId = resMap.get("orderId") + "";
			retMap.put("orderId", buyOrderId);
		}
		
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("userId", null);
		reqMap.put("type", "12");//商城购买
		//送加息券
//		rateRisesCouponsService.shareKNotifyAddCoupons(reqMap);
//		retMap.put("loanId", resMap.get("loanId"));	
		retMap.put("cpType", resMap.get("cpType"));
		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg", "");
		retMap.put("resmsg_cn", "");
		return retMap;
	}
	
	/**
	 * 活动送理财(E400001)
	 */
	public Map<String,Object> buyLoan(Map<String,String> map) throws Exception{
		if(map == null || map.size() == 0){
			return null;
		}
		
		String transCode = "E400001";
		
		String userId = (null == map.get("userId") ? "" : map.get("userId"));
		String lcOrderId = (null == map.get("lcOrderId") ? "" : map.get("lcOrderId"));
		String financeType = (null == map.get("financeType") ? "" : map.get("financeType"));
		String buyQuantity = (null == map.get("buyQuantity") ? "" : map.get("buyQuantity"));// 购买数量
		String investAmount = (null == map.get("investAmount") ? "" : map.get("investAmount"));// 投资金额
		String expectIncomeAmount = (null == map.get("expectIncomeAmount") ? "" : map.get("expectIncomeAmount"));// 预期收益
		String term = map.get("term") == null ? "" : map.get("term");
		String annualRate = map.get("annualRate") == null ? "" : map.get("annualRate");
		String buyMedia = (null == map.get("buyMedia") ? "LBWX":map.get("buyMedia"));
		String agreementNo = (null == map.get("agreementNo") ? "" : map.get("agreementNo"));
		String assetNo = (null == map.get("assetNo") ? "" : map.get("assetNo"));
		String agreementAutoid = (null == map.get("agreementAutoid") ? "" : map.get("agreementAutoid"));
		// 设置报文体报文数据
		Map<String, Object> pageModel = new HashMap<String, Object>();
		pageModel.put("userId", userId);
		pageModel.put("buyQuantity", buyQuantity);
		pageModel.put("investAmount", investAmount);
		pageModel.put("expectIncomeAmount", expectIncomeAmount);
		pageModel.put("term", term);
		pageModel.put("annualRate", annualRate);
		pageModel.put("currency", "CNY");// 货币单位:CNY人民币，USD美元
		pageModel.put("cyclematchtype", 3);// 资金流转方式：1--收益循环投资—本息循环；2—收益每月返还—本金循环3—不循环
		pageModel.put("channelId", lcOrderId);//t_finance_info 表的 id
		pageModel.put("financeType", financeType);//t_finance_info 表的 financeType
		pageModel.put("buyMedia", buyMedia);
		pageModel.put("agreementNo", agreementNo);//t_finance_info 表的 id
		pageModel.put("assetNo", assetNo);
		pageModel.put("agreementAutoid", agreementAutoid);
		
		Map resmap = coreUse(userId, transCode, pageModel);
		return resmap;
	}
	
	/**
	 * 调用核心接口
	 */
	@Transactional
	private Map coreUse(String userId,String transCode,Map<String, Object> pageModel) throws Exception {
		// 设置报文体报文数据
		String jsonStr = CommonUtil.constructJsonStr(transCode, userId, pageModel);// 构建json字符串
		TcpMinaClient tcpMinaClient = new TcpMinaClient();
		String rtnStr = tcpMinaClient.sendMessage(jsonStr);

		if(StringUtils.isBlank(rtnStr)){
			logger.debug("调用核心接口发生异常" + ",接口id：" + transCode);
			throw new Exception("调用核心接口发生异常" + ",接口id：" + transCode);
		}
		
		rtnStr = rtnStr.substring(8, rtnStr.length());
		// 转化json数据为页面模型数据格式
		Map rtnMap = (HashMap) JsonUtil.getObjectFromJsonString(rtnStr,
				HashMap.class);

		return rtnMap;
	}


	@Override
	public String queryMyAccountDetail(Map<String, String> map)
			throws Exception {
		/**
		 * 调用核心接口 E350003查询我的账户详情信息
		 * */
		String transCode = "E350003";
		Map<String, Object> queryCoreMap = new HashMap<String, Object>();
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		queryCoreMap.put("userId", map.get("userId"));

		String jsonStr = CommonUtil.constructJsonStr(transCode,
				map.get("userId").toString(), queryCoreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		
		if (Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))) {
			JSONObject accountDetail = jsonObject.fromObject(jsonObject.get("accountDetail"));
			rtnMap.put("acctBalance", accountDetail.get("acctBalance"));
			rtnMap.put("amountSum", accountDetail.get("investAmountSum"));
		} else {
			logger.debug("=====E350003核心接口调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode")
					+ "；  resmsg：" + jsonObject.getString("resmsg"));
			rtnMap.put("acctBalance", "0");
			rtnMap.put("amountSum", "0");
		}
		return CommonUtil.setResultStringCn(rtnMap, Consts.SUCCESS_CODE,
				Consts.SUCCESS_DESCRIBE, "");
	}

	@Override
	public Map<String,Object> goodsDetailImg(Map<String, Object> map) throws Exception{
		Map<String, Object> retMap = new HashMap<String,Object>();
		if((null != map.get("goodsId") && !"".equals(map.get("goodsId")))) {
			Map<String, Object> goodsMap = shopBuyDao.getGoodsDetailImg(map);
			if (null != goodsMap)
			return goodsMap;
		}
		
		retMap.put("picDetailLink", "");
		retMap.put("goodsDetailImgHead", "");
		retMap.put("goodsDetailImgBottom", "");
		return retMap;
	}
	
	@Async
	@Override
	public void sendMeidaAndSMS(String userId, String finaceId,
			String productName, String goodsName, String amount,
			String buyQuantity) throws Exception {
		// 封装用户ID
		WeixinMediaBinding mediaBinding = new WeixinMediaBinding();
		mediaBinding.setUserId(Integer.parseInt(userId));

		// 先推送微信，微信成功不发短信，失败再发短信
		String mobile = captchaService.getMobileById(userId);// 通过用户ID查询使用手机号
		String mediaUid = weixinBindingService.queryMediaUid(mediaBinding);// 通过用户ID实体类查询微信标识

		// TODO 逻辑判断
		if (null == mediaUid || "null".equalsIgnoreCase(mediaUid)
				|| "".equalsIgnoreCase(mediaUid)) {
			logger.info("[推送短信息]因手机号：" + mobile + "并未绑定微信");
			// 发送短信
			String smsNo = "sms02001";// config_sms表中参数
			if (StringUtils.isBlank(userId) || StringUtils.isBlank(smsNo)
					|| StringUtils.isBlank(amount)) {
				logger.debug("deposit/join sendSMS 传入参数为空");
			}
			try {
				// 发送短信
				if (StringUtils.isEmpty(productName)) {
					sMSService.getSMS(userId, smsNo, amount);
				} else {
					sMSService.getSMS(userId, smsNo, amount, productName);
				}
			} catch (Exception e) {
				logger.error("deposit/join sendSMS异常:" + e.getCause());
			}
		} else {
			Map<String, String> weixinTMap = new HashMap<String, String>();
			weixinTMap.put("mediaUid", mediaUid);// 微信用户唯一标识
			if ("109".equalsIgnoreCase(finaceId)) {
				weixinTMap.put("productInfo", "铃铛宝活期");// 产品内容
			} else {
				if ("108".equalsIgnoreCase(finaceId)) {
					weixinTMap.put("productInfo", productName);// 产品内容
				} else {
					weixinTMap.put("productInfo", "铃铛宝");// 产品内容
				}
			}
			weixinTMap.put("productName", productName);// 产品名称
			weixinTMap.put("goodsName", goodsName);// 商品名称
			weixinTMap.put("amount", amount);// 购买金额
			weixinTMap.put("buyQuantity", buyQuantity);// 购买数量
			weixinTMap.put("functionScope", "shopBuy");// 购买金额

			boolean sendRusult = SendWeiXinUtil.sendWeiXin(weixinTMap);
			if (!sendRusult) {
				logger.info("[微信推送失败][推送短信息]因手机号：" + mobile
						+ "并未绑定微信或者未关注联币钱包微信号");
				// 发送短信
				String smsNo = "sms02001";// config_sms表中参数
				if (StringUtils.isBlank(userId) || StringUtils.isBlank(smsNo)
						|| StringUtils.isBlank(amount)) {
					logger.debug("deposit/join sendSMS 传入参数为空");
				}
				try {
					// 发送短信
					if (StringUtils.isEmpty(productName)) {
						sMSService.getSMS(userId, smsNo, amount);
					} else {
						sMSService.getSMS(userId, smsNo, amount, productName);
					}
				} catch (Exception e) {
					logger.error("deposit/join sendSMS异常:" + e.getCause());
				}
			} else {
				logger.info("[微信推送]手机号：" + mobile + "推送成功");
			}
		}

	}
}

